from django.test import TestCase
from mixer.backend.django import mixer

from api.models import Run, Record, User
from api.views.algorithm.views import ALGORITHM

import random, json
from datetime import datetime, timedelta

"""

urlpatterns = [
    path("algorithm-query", algorithm_query),
    path("algorithm-run", algorithm_run),
    path("algorithm-result-query", algorithm_result_query),
    path("algorithm-result-detail", algorithm_result_detail),
    path("algorithm-interrupt", algorithm_interrupt),
    path("algorithm-result-delete", algorithm_result_delete),
]


"""

record_nums = 30


def insert_test_data():
    run_nums = 0
    # 插入 30 条已完成的算法，并将其中的 [0, 1] 插入 Run 中
    for i in range(record_nums):
        # 随机选择一个算法 ID
        algorithm_id = random.choice(list(ALGORITHM.keys()))
        algorithm_status = random.choice([0, 1, 2, 3])
        if algorithm_status == 2:
            d_result = f"这是算法 {algorithm_id} 的运行结果"
        else:
            d_result = ""

        record = mixer.blend(
            Record,
            status=algorithm_status,  # 假设状态是 0, 1, 2, 3
            params=json.dumps(
                {
                    "user_name": "aiops@admin",
                    "algorithm": {
                        "id": algorithm_id,
                        "name": ALGORITHM[algorithm_id]["name"],
                        "start_time": (
                            datetime.now() - timedelta(days=i + 1)
                        ).timestamp(),
                        "end_time": (datetime.now() - timedelta(days=i)).timestamp(),
                    },
                }
            ),
            create_time=datetime.now(),
            result=json.dumps({"result": d_result}),
        )

        if record.status in [0, 1]:
            run_nums += 1
            run = mixer.blend(
                Run,
                id=record.id,
                status=record.status,
                params=record.params,  # 假设状态是 0, 1
            )

    print(f"run 总数为: {run_nums}.")
    print(f"record 总数为: {record_nums}.")


def delete_test_data():
    Run.objects.all().delete()
    Record.objects.all().delete()


class AlgorithmTestCase(TestCase):
    def __init__(self, methodName: str = "runTest") -> None:
        super().__init__(methodName)

    def setUp(self):
        self.user = mixer.blend(User, username="aiops@admin")
        delete_test_data()
        insert_test_data()

    def tearDown(self):
        delete_test_data()

    def test_algorithm_query(self):
        response = self.client.get("/algorithm-query")
        self.assertTrue(response.status_code == 200)

    def test_algorithm_run(self):
        response = self.client.post(
            "/algorithm-run",
            {
                "id": "1",
                "start_time": datetime(2024, 5, 5, 0, 0, 0).timestamp(),
                "end_time": datetime(2024, 5, 5, 0, 10, 0).timestamp(),
                "name": "not determined",
            },
            content_type="application/json",
        )
        self.assertTrue(response.status_code == 200)
        # print(response.json()["data"])

    def test_algorithm_interrupt(self):
        run = Run.objects.first()

        response = self.client.delete(
            "/algorithm-interrupt",
            {
                "id": run.id,
            },
            content_type="application/json",
        )

        self.assertTrue(response.status_code == 200)

    def test_algorithm_result_detail(self):
        # 未完成的算法
        record = Record.objects.filter(status=0).first()
        response = self.client.get("/algorithm-result-detail", {"id": record.id})
        self.assertTrue(response.status_code == 200)
        # print(response.json())

        # 已完成的算法
        record = Record.objects.filter(status=2).first()
        response = self.client.get("/algorithm-result-detail", {"id": record.id})
        self.assertTrue(response.status_code == 200)

    def test_algorithm_result_query(self):
        response = self.client.get(
            "/algorithm-result-query",
        )
        self.assertTrue(response.status_code == 200)

    def test_algorithm_result_delete(self):
        # try
        id_list = [1, 2, 3, 4]
        response = self.client.delete(
            "/algorithm-result-delete",
            {
                "id_list": id_list,
            },
            content_type="application/json",
        )
        self.assertTrue(response.status_code == 200)

        # except
        id_list = [1, 2, 3, 4, 1000000]
        response = self.client.delete(
            "/algorithm-result-delete",
            {
                "id_list": id_list,
            },
            content_type="application/json",
        )
        self.assertTrue(response.status_code == 200)
